using DeviceRepairWorkflow.Api.Data;
using DeviceRepairWorkflow.Api.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace DeviceRepairWorkflow.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class ExternalVendorsController : ControllerBase
{
    private readonly ApplicationDbContext _context;

    public ExternalVendorsController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public async Task<ActionResult<IEnumerable<ExternalVendor>>> GetExternalVendors()
    {
        return await _context.ExternalVendors
            .Where(v => v.IsActive)
            .OrderBy(v => v.CompanyName)
            .ToListAsync();
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<ExternalVendor>> GetExternalVendor(int id)
    {
        var vendor = await _context.ExternalVendors.FindAsync(id);

        if (vendor == null)
        {
            return NotFound();
        }

        return vendor;
    }

    [HttpPost]
    public async Task<ActionResult<ExternalVendor>> CreateExternalVendor(ExternalVendor vendor)
    {
        vendor.CreatedAt = DateTime.Now;
        _context.ExternalVendors.Add(vendor);
        await _context.SaveChangesAsync();

        return CreatedAtAction(nameof(GetExternalVendor), new { id = vendor.Id }, vendor);
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> UpdateExternalVendor(int id, ExternalVendor vendor)
    {
        if (id != vendor.Id)
        {
            return BadRequest();
        }

        _context.Entry(vendor).State = EntityState.Modified;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!ExternalVendorExists(id))
            {
                return NotFound();
            }
            throw;
        }

        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteExternalVendor(int id)
    {
        var vendor = await _context.ExternalVendors.FindAsync(id);
        if (vendor == null)
        {
            return NotFound();
        }

        // Soft delete
        vendor.IsActive = false;
        await _context.SaveChangesAsync();

        return NoContent();
    }

    private bool ExternalVendorExists(int id)
    {
        return _context.ExternalVendors.Any(e => e.Id == id);
    }
} 